<template>
  <div class="flight-manage">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="showAddDialog = true">
        <i class="el-icon-plus"></i> 发布航班
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索航班号/城市"
        class="search-input"
        clearable
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>

    <!-- 航班列表 -->
    <el-table
      v-loading="loading"
      :data="flights"
      border
      style="width: 100%"
    >
      <el-table-column prop="flightNumber" label="航班号" width="120" />
      <el-table-column label="航线" width="200">
        <template slot-scope="scope">
          {{ scope.row.departureCity }} - {{ scope.row.arrivalCity }}
        </template>
      </el-table-column>
      <el-table-column prop="departureTime" label="出发时间" width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.departureTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="arrivalTime" label="到达时间" width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.arrivalTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="flightDuration" label="飞行时长" width="120" />
      <el-table-column prop="aircraftType" label="机型" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'"
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status === 'ACTIVE' ? '下架' : '上架' }}
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑航班对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="showAddDialog" width="650px">
      <el-form :model="flightForm" :rules="rules" ref="flightForm" label-width="100px">
        <el-form-item label="航班号" prop="flightNumber">
          <el-input v-model="flightForm.flightNumber" placeholder="请输入航班号"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出发城市" prop="departureCity">
              <el-select v-model="flightForm.departureCity" filterable placeholder="请选择出发城市">
                <el-option
                  v-for="city in cities"
                  :key="city.value"
                  :label="city.label"
                  :value="city.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到达城市" prop="arrivalCity">
              <el-select v-model="flightForm.arrivalCity" filterable placeholder="请选择到达城市">
                <el-option
                  v-for="city in cities"
                  :key="city.value"
                  :label="city.label"
                  :value="city.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出发时间" prop="departureTime">
              <el-date-picker
                v-model="flightForm.departureTime"
                type="datetime"
                placeholder="选择出发时间"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到达时间" prop="arrivalTime">
              <el-date-picker
                v-model="flightForm.arrivalTime"
                type="datetime"
                placeholder="选择到达时间"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机型" prop="aircraftType">
              <el-input v-model="flightForm.aircraftType" placeholder="请输入机型"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="飞行时长" prop="flightDuration">
              <el-input v-model="flightForm.flightDuration" placeholder="请输入飞行时长"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 票价设置 -->
        <el-divider content-position="left">票价设置</el-divider>
        <div class="ticket-prices">
          <el-row :gutter="20" v-for="(ticket, index) in flightForm.tickets" :key="index">
            <el-col :span="8">
              <el-form-item :label="'票型' + (index + 1)" :prop="'tickets.' + index + '.type'">
                <el-select v-model="ticket.type" placeholder="选择票型">
                  <el-option label="经济舱" value="ECONOMY"></el-option>
                  <el-option label="商务舱" value="BUSINESS"></el-option>
                  <el-option label="头等舱" value="FIRST"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item :prop="'tickets.' + index + '.price'">
                <el-input-number v-model="ticket.price" :min="0" placeholder="价格"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item :prop="'tickets.' + index + '.quantity'">
                <el-input-number v-model="ticket.quantity" :min="0" placeholder="数量"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="danger" icon="el-icon-delete" circle @click="removeTicket(index)" v-if="index > 0"></el-button>
            </el-col>
          </el-row>
          <el-button type="primary" icon="el-icon-plus" @click="addTicket" plain>添加票型</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitFlight">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'FlightManage',
  data() {
    // 验证出发时间和到达时间
    const validateArrivalTime = (rule, value, callback) => {
      if (value && this.flightForm.departureTime) {
        if (moment(value).isBefore(this.flightForm.departureTime)) {
          callback(new Error('到达时间不能早于出发时间'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      loading: false,
      flights: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchQuery: '',
      showAddDialog: false,
      editingFlightId: null,
      flightForm: {
        flightNumber: '',
        departureCity: '',
        arrivalCity: '',
        departureTime: '',
        arrivalTime: '',
        aircraftType: '',
        flightDuration: '',
        tickets: [{
          type: 'ECONOMY',
          price: 0,
          quantity: 0
        }]
      },
      rules: {
        flightNumber: [
          { required: true, message: '请输入航班号', trigger: 'blur' },
          { pattern: /^[A-Z0-9]{2,8}$/, message: '航班号格式不正确', trigger: 'blur' }
        ],
        departureCity: [
          { required: true, message: '请选择出发城市', trigger: 'change' }
        ],
        arrivalCity: [
          { required: true, message: '请选择到达城市', trigger: 'change' }
        ],
        departureTime: [
          { required: true, message: '请选择出发时间', trigger: 'change' }
        ],
        arrivalTime: [
          { required: true, message: '请选择到达时间', trigger: 'change' },
          { validator: validateArrivalTime, trigger: 'change' }
        ],
        aircraftType: [
          { required: true, message: '请输入机型', trigger: 'blur' }
        ],
        flightDuration: [
          { required: true, message: '请输入飞行时长', trigger: 'blur' }
        ]
      },
      cities: [
        { value: '北京', label: '北京' },
        { value: '上海', label: '上海' },
        { value: '广州', label: '广州' },
        { value: '深圳', label: '深圳' },
        { value: '成都', label: '成都' },
        { value: '杭州', label: '杭州' },
        { value: '西安', label: '西安' },
        { value: '重庆', label: '重庆' },
        { value: '南京', label: '南京' },
        { value: '武汉', label: '武汉' }
      ]
    }
  },
  computed: {
    dialogTitle() {
      return this.editingFlightId ? '编辑航班' : '���布航班'
    }
  },
  created() {
    this.fetchFlights()
  },
  methods: {
    async fetchFlights() {
      this.loading = true
      try {
        const response = await axios.get('/manage/flights', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            query: this.searchQuery
          }
        })
        if (response.data.code === 0) {
          this.flights = response.data.data.list
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取航班列表失败')
        }
      } catch (error) {
        console.error('Error fetching flights:', error)
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    formatDateTime(datetime) {
      return moment(datetime).format('YYYY-MM-DD HH:mm')
    },
    getStatusType(status) {
      return status === 'ACTIVE' ? 'success' : 'info'
    },
    getStatusText(status) {
      return status === 'ACTIVE' ? '已上架' : '已下架'
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchFlights()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchFlights()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchFlights()
    },
    resetForm() {
      this.editingFlightId = null
      this.$refs.flightForm.resetFields()
      this.flightForm = {
        flightNumber: '',
        departureCity: '',
        arrivalCity: '',
        departureTime: '',
        arrivalTime: '',
        aircraftType: '',
        flightDuration: '',
        tickets: [{
          type: 'ECONOMY',
          price: 0,
          quantity: 0
        }]
      }
    },
    addTicket() {
      this.flightForm.tickets.push({
        type: 'ECONOMY',
        price: 0,
        quantity: 0
      })
    },
    removeTicket(index) {
      this.flightForm.tickets.splice(index, 1)
    },
    handleEdit(flight) {
      this.editingFlightId = flight.flightId
      this.flightForm = { ...flight }
      this.showAddDialog = true
    },
    async handleToggleStatus(flight) {
      try {
        const action = flight.status === 'ACTIVE' ? 'deactivate' : 'activate'
        const response = await axios.post(`/manage/flights/${flight.flightId}/${action}`)
        if (response.data.code === 0) {
          this.$message.success(flight.status === 'ACTIVE' ? '航班已下架' : '航班已上架')
          this.fetchFlights()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        console.error('Error toggling flight status:', error)
        this.$message.error('网络错误，请稍后重试')
      }
    },
    async handleDelete(flight) {
      try {
        await this.$confirm('确定要删除该航班吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await axios.delete(`/manage/flights/${flight.flightId}`)
        if (response.data.code === 0) {
          this.$message.success('航班已删除')
          this.fetchFlights()
        } else {
          this.$message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Error deleting flight:', error)
          this.$message.error('网络错误，请稍后重试')
        }
      }
    },
    async submitFlight() {
      try {
        await this.$refs.flightForm.validate()
        
        const url = this.editingFlightId 
          ? `/manage/flights/${this.editingFlightId}`
          : '/manage/flights'
        const method = this.editingFlightId ? 'put' : 'post'
        
        const response = await axios[method](url, this.flightForm)
        if (response.data.code === 0) {
          this.$message.success(this.editingFlightId ? '航班已更新' : '航班已发布')
          this.showAddDialog = false
          this.resetForm()
          this.fetchFlights()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        console.error('Error submitting flight:', error)
        this.$message.error('网络错误，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.flight-manage {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.ticket-prices {
  padding: 10px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.el-divider {
  margin: 20px 0;
}
</style> 